package com.lanfan.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lanfan.entity.Users;
import com.lanfan.entity.UsersExample;
import com.lanfan.entity.UsersPage;
import com.lanfan.mapper.UsersMapper;
import com.lanfan.service.UsersService;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UsersServiceImpl implements UsersService {
    @Resource
    private UsersMapper usersMapper;


    @Override
    public void save(Users users) {
        if (users.getUserId()!= null) {
            update(users);
        }else {
            insert(users);
        }
    }
    private void update(Users users) {
        usersMapper.updateByPrimaryKeySelective(users);
    }

    private void insert(Users users) {
        usersMapper.insert(users);
    }

    @Override
    public void delete(Integer user_id) {
        usersMapper.deleteByPrimaryKey(user_id);
    }

    @Override
    public void search(UsersPage userspage) {
        PageHelper.startPage(userspage.getPageIndex(), userspage.getPageSize());
        UsersExample usersExample = new UsersExample();
        UsersExample.Criteria criteria = usersExample.createCriteria();

        if (!StringUtils.isEmpty(userspage.getUsername())) {
            criteria.andUsernameLike("%" + userspage.getUsername() + "%");
        }
        List<Users> usersList = usersMapper.selectByExample(usersExample);
        PageInfo<Users> pageInfo = new PageInfo<>(usersList);
        userspage.setTotal((int)pageInfo.getTotal());
        userspage.setList(usersList);
    }

    @Override
    public Users findByPhone(String phone) {
        UsersExample usersExample = new UsersExample();
        UsersExample.Criteria criteria = usersExample.createCriteria();
        criteria.andPhoneEqualTo(phone);
        return usersMapper.selectByExample(usersExample).get(0);
    }
}
